const db=require('../util/db.js');
const mysql=require('mysql');
exports.getLastMessageList=(user_id,callback_service)=>{
    let sql=mysql.format("select u1.id,SUBSTRING_INDEX(GROUP_CONCAT(chat_message.content ORDER BY chat_message.id DESC SEPARATOR '||'),'||',1) content,u1.nickname,u1.head_img from chat_message right join chat_user as u1 on chat_message.send_user_id=u1.id where chat_message.receive_user_id= ? and chat_message.send_user_id!= ? and chat_message.del=0 group by chat_message.send_user_id order by chat_message.create_time desc",[user_id,user_id]);
    db.query(sql,(data,error)=>{
        callback_service(data,error);
    });
}
exports.getMessageByFriend=(message,callback_service)=>{
    let sql=mysql.format("select send_user_id,content,create_time from chat_message where del=0 and ((send_user_id= ? and receive_user_id= ? ) or (send_user_id= ? and receive_user_id= ? )) order by create_time",[message.send_user_id,message.receive_user_id,message.receive_user_id,message.send_user_id]);
    db.query(sql,(data,error)=>{
        callback_service(data,error);
    });
}
exports.saveMessage=(message,callback_service)=>{
    let sql=mysql.format("insert into chat_message(send_user_id,receive_user_id,content) values (?,?,?)",[message.send_user_id,message.receive_user_id,message.content]);
    db.query(sql,(data,error)=>{
        callback_service(data,error);
    });
}
exports.getMessageCountByUser=(id,time_start,time_end,callback_service)=>{
    let sql=mysql.format("select date_format(create_time,'%Y-%m-%d') as date,count(*) as count from chat_message where send_user_id = ? and create_time between ? and ? group by date_format(create_time,'%Y-%m-%d')",[id,time_start,time_end]);
    db.query(sql,(data,error)=>{
        callback_service(data,error);
    });
}